<template>
  <div v-if="COMPLEXSTATE">
    <div class="selection-container">
      <el-cascader v-if="!isStudent" v-model="selectedOptions" :options="cascaderOptions" :show-all-levels="false" placement="right-start" :props="{ expandTrigger: 'hover' }" placeholder="请选择专业和班级" @change="getAllComplex" filterable class="flex-item"></el-cascader>
      <el-select @change="getAllComplex" v-model="selectedStatus" placeholder="请选择审批状态" class="flex-item">
        <el-option label="已审批" value="1"></el-option>
        <el-option label="未审批" value="0"></el-option>
        <el-option label="未通过" value="3"></el-option>
      </el-select>
    </div>
    <el-input ref='searchInput' v-model="NameOrStudentAccount" autocapitalize="off" autocomplete="off" autocorrect="off" autofocus clearable icon="Search" placeholder="搜索..." spellcheck="false" style="width: 20%;" type="text" @change="getAllComplex"/>
    <el-button icon="search" style="position: relative; left: 5px" type="primary" @click="getAllComplex">搜索</el-button>
    <el-button type="success" @click="exportToExcel">导出Excel</el-button>
    <el-table :data="ComplexForm" border style="width: 100%" :header-cell-style="{'text-align':'center'}" :cell-style="{'text-align':'center'}" height="80vh" v-model="selectedRow" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="year" label="综测年度" :filter-method="FilterHandler" :filters="yearHeaderSelect" :filter-multiple="false" :default-value="defaultYear" width="150" sortable></el-table-column>
      <el-table-column prop="name" label="姓名" width="150" sortable></el-table-column>
      <el-table-column prop="accountNo" label="学号" width="150" sortable></el-table-column>
      <el-table-column prop="gradeNo" label="年级" :filter-method="FilterHandler" :filters="gradeNoHeaderSelect" :filter-multiple="false" width="150" sortable></el-table-column>
      <el-table-column prop="classNo" label="班级" width="150" sortable></el-table-column>
      <el-table-column prop="majorName" label="专业" :filter-method="FilterHandler" :filters="majorNameHeaderSelect" :filter-multiple="false" width="200" sortable></el-table-column>
      <el-table-column prop="scoreA1" label="A1思想品德" width="150" sortable></el-table-column>
      <el-table-column prop="avgCreditPoint" label="A2平均学分绩点" width="170" sortable></el-table-column>
      <el-table-column prop="scoreA2" label="A2学业成绩" width="150" sortable></el-table-column>
      <el-table-column prop="scoreA3" label="A3身心素质" width="150" sortable></el-table-column>
      <el-table-column prop="scoreB1" label="B1社会工作与对外交流" width="210" sortable></el-table-column>
      <el-table-column prop="scoreB2" label="B2公益服务与社会实践" width="210" sortable></el-table-column>
      <el-table-column prop="scoreB3" label="B3文体艺活动" width="150" sortable></el-table-column>
      <el-table-column prop="scoreB4" label="B4学术与创新创业" width="180" sortable></el-table-column>
      <el-table-column prop="scoreAll" label="综测总分" width="150" sortable></el-table-column>
      <el-table-column prop="ranking" label="综测排名" width="150" sortable :sort-method="(a,b)=>{return a.ranking - b.ranking}"></el-table-column>
      <el-table-column prop="gpaRank" label="A2成绩排名" width="150" sortable :sort-method="(a,b)=>{return a.gpaRank - b.gpaRank}"></el-table-column>
      <el-table-column prop="notNum" label="不及格门次" width="150" sortable></el-table-column>
      <el-table-column prop="score" label="国测成绩" width="150" sortable></el-table-column>
      <el-table-column align="center" label="操作" width="300">
        <template v-slot="scope">
          <el-button size="small" type="primary" @click="detailedInformation(scope)">查看详情</el-button>
          <el-button size="small" type="warning" @click="changeComplex(scope)">修改综测</el-button>
          <el-button size="small" type="success" @click="this.$router.push({path:'/ComplexApproval',query: {accountNo:scope.row.accountNo,year:scope.row.year}})">综测审批
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination class="pagination" :page-size="pageSize" small :pager-count="5"
                   :page-sizes="[50, 100 , 200 , 500,1000,2000,5000]" :total="total"
                   layout="total, sizes, prev, pager, next" @size-change="handleSizeChange"
                   @current-change="handleCurrentChange"></el-pagination>
  </div>
  <div style="text-align: center;font-size: 50px" v-else>
    综测未开放
  </div>
  <el-dialog v-model="this.$store.state.complexDetail" :close-on-click-modal="false" title="综测详情信息" width="850px">
    <Complex v-if="this.$store.state.complexDetail"/>
  </el-dialog>
</template>
<script>


import request from "@/util/request.js";
import * as XLSX from "xlsx";
import Information from "@/template/Information.vue";
import Complex from "@/template/Complex.vue";
import {COMPLEX_MANAGER} from "@/util/config.js";
import {year,COMPLEXSTATE} from "../../../public/static/config.js";

export default {
  components: {Complex, Information},
  data() {
    return {
      COMPLEXSTATE:COMPLEXSTATE,
      isStudent: false,
      pageNum: 1, //页码
      pageSize: 50,  //页长
      total: 0,  //总表长
      NameOrStudentAccount:"",
      ComplexForm:[],
      cascaderOptions: [],//所有班级
      selectedOptions: [],//选中班级数据
      selectedStatus: "0",
      selectedRow: [], // 选中行
      yearHeaderSelect: [{
        text: '2023',
        value: '2023'
      },{
        text: '2024',
        value: '2024'
      },{
      },{
        text: '2025',
        value: '2025'
      },{
      },{
        text: '2026',
        value: '2026'
      },{
        text: '其他',
        value: '其他'
      }],
      defaultYear: '2024',
      gradeNoHeaderSelect: [{
        text: '2021',
        value: '2021'
      }, {
        text: '2022',
        value: '2022'
      },{
        text: '2023',
        value: '2023'
      },{
        text: '2024',
        value: '2024'
      },{
        text: '其他',
        value: '其他'
      }],
      majorNameHeaderSelect: [{
        text: '计算机科学与技术',
        value: '计算机科学与技术'
      },{
        text: '物联网工程',
        value: '物联网工程'
      },{
        text: '电子信息工程',
        value: '电子信息工程'
      },{
        text: '通信工程',
        value: '通信工程'
      },{
        text: '软件工程',
        value: '软件工程'
      },{
        text: '轨道交通信号与控制',
        value: '轨道交通信号与控制'
      },{
        text: '计算机科学与技术(专升本)',
        value: '计算机科学与技术(专升本)'
      },{
        text: '其他',
        value: '其他'
      }]
    };
  },
  created() {
    if (COMPLEXSTATE){
      let role = JSON.parse(localStorage.getItem("user")).roleNo;
      // 如果是授予的学生权限
      if (role.includes(COMPLEX_MANAGER)){
        this.isStudent=true
        this.selectedOptions.push("")
        this.selectedOptions.push("")
        this.selectedOptions.push(JSON.parse(localStorage.getItem("user")).classNo)
        this.getAllComplex()
      }else {
        this.getClass()
        this.getAllComplex();
      }
    }
  },
  methods:{
    changeComplex(scope) {
      // 教师修改综测，在Complex页面不进行跳转
      this.$store.commit('setChangeComplexTrue')
      this.$store.commit('setAccountN0', scope.row.accountNo)
      this.$store.commit('setYear', scope.row.year)
      this.$router.push({path: '/UploadComplex', query: {accountNo: scope.row.accountNo, year: scope.row.year}})
    },
    /**
     * 查看详情
     * @param scope
     */
    detailedInformation(scope) {
      console.log(this.$store.state.complexDetail)
      this.$store.commit('complexDetailSetTrue')
      this.$store.commit('setAccountN0', scope.row.accountNo)
      this.$store.commit('setYear', scope.row.year)
      console.log(this.$store.state.complexDetail)
    },
    /**
     * 获取班级
     */
    getClass() {
      request.get("/info_class/getClassNoByAccount?accountNo="+JSON.parse(localStorage.getItem("user")).accountNo).then(res => {
        console.log(res.data.data)
        this.cascaderOptions = res.data.data
      })
    },
    /**
     * 获取选中班级的数据
     */
    // handleCascaderChange() {
    //   let classNo = this.selectedOptions.at(2)
    //   request.get("/complex_related/getListByClassNoAndYear?classNo=" + classNo + "&year=" + this.year + "&state=" + this.selectedStatus).then(res => {
    //     this.ComplexForm = res.data.data;
    //   })
    // },

    getAllComplex(){
      let classNo = "1" //不可以删
      if (this.selectedOptions.at(2) !== undefined) {
        classNo = this.selectedOptions.at(2)
      }
      request.get("/info_complex/getAllComplex?name=" + this.NameOrStudentAccount + "&accountNo=" + this.NameOrStudentAccount + "&pageNum=" + this.pageNum + "&pageSize=" + this.pageSize + "&classNo=" + classNo + "&state=" + this.selectedStatus+"&year="+year).then(res => {
        if (res.data.code === '200') {
          for (let key in res.data.data) {
            if (key === "records") {
              this.ComplexForm = res.data.data[key];
            } else if (key === "total") {
              this.total = res.data.data[key];
            }
          }
        }
      })
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getAllComplex();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getAllComplex();
    },
    // 选行
    handleSelectionChange(val) {
      this.selectedRow = val;
    },
    exportToExcel() {
      this.$nextTick(() => {
        // 获取 el-table 中的当前显示数据
        const tableData = this.selectedRow;
        // 确保数据存在
        if (tableData && tableData.length > 0) {
          // 提取所需的字段，并按照你想要的顺序和列名重组数据
          const formattedData = tableData.map(item => ({
            学号: item.accountNo,
            姓名: item.name,
            年级: item.gradeNo,
            班级: item.classNo,
            专业: item.majorName,
            A1思想品德: item.scoreA1,
            A2平均学分绩点: item.avgCreditPoint,
            A2学业成绩: item.scoreA2,
            A3身心素质: item.scoreA3,
            B1社会工作与对外交流: item.scoreB1,
            B2公益服务与社会实践: item.scoreB2,
            B3文体艺活动: item.scoreB3,
            B4学术与创新创业: item.scoreB4,
            综测总分: item.scoreAll,
            综测排名: item.ranking,
            A2成绩排名: item.gpaRank,
            不及格门次: item.notNum,
            国测成绩: item.score,
          }));

          // 将数据转换为 Excel 格式
          const worksheet = XLSX.utils.json_to_sheet(formattedData);
          const workbook = XLSX.utils.book_new();
          XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

          // 下载 Excel 文件
          XLSX.writeFile(workbook, 'student_Complex.xlsx');
        } else {
          // 提示用户没有数据可供导出
          alert('没有数据可供导出！');
        }
      });
    },

    FilterHandler(value, row, column) {
      const property = column['property'];
      // 如果值是“其他”，则返回除了已有选项之外的字段
      if (value === '其他') {
        return !column['filters'].some(filter => filter.value === row[property]);
      }
      // 否则按照正常逻辑进行筛选
      return row[property] === value;
    },
  }
}
</script>

<style scoped>
.selection-container {
  display: flex;
}
</style>
